# -*- coding: utf-8 -*-
import redis
import threading

ENCODING = 'UTF-8'


class RedisUtil(object):
    """
    Redis 工具类
    get_lock 获取锁对象,然后使用成对函数 acquire 和 release 去使用它
    get_redis_client 获取Redis操作对象
    get_key 用于生成Redis key, Redis key的由三部分组成，比如我们要记录一下某个用户上次登录的时间，可以使用
        模块:user 类别: last_login_time 用户的key:zhangsan, 那么最终的key就是 user:last_login_time:zhangsan
        这是单独的key，如果是一个团体，容器为hash的key，就这样组成最终的key
        模块:user 类别: login 详细的key: last_login_time, 那么最终的key就是 user:login:last_login_time
            zhangsan 就是这个团体下面代表具体某个用户的key
    pubsub 注册一个频道的订阅函数
    publish 发送消息到某个频道
    """
    _pool = None
    _callbacks = dict()
    _func_lock = threading.RLock()

    def __init__(self, host: str, port: int):
        """
        init redis connection pool
        :param host: server address of redis
        :param port: server l of redis
        """
        self._pool = redis.ConnectionPool(host=host, port=port, max_connections=100, decode_responses=True)

    def get_lock(self, name, blocking_timeout):
        """
        Get the lock object, use acquire and release method in this object to use it
        :param name: key to lock
        :param blocking_timeout: indicates the maximum amount of time in seconds to
        spend trying to acquire the lock
        :return:
        """
        _redis = redis.StrictRedis(connection_pool=self._pool,  decode_responses=True)
        return _redis.lock(name, blocking_timeout)

    def get_redis_client(self) -> redis.Redis:
        """
        Get redis client
        :return: redis client
        """
        _redis = redis.StrictRedis(connection_pool=self._pool, decode_responses=True)
        return _redis


redis_util: RedisUtil = None
